using UnityEngine;
using Noise;
using Render;

public class DerivativeTexture : GUITextureNode
{
    public float UVScale = 4.0f;
    public float UVShift = 0.0f;
    public float NoiseScale = 0.5f;
    public float NoiseShift = 0.5f;    
    public int Octaves = 1;
    public float Lacunarity = 1.92f;
    public float Gain = 0.5f;

    public override void DrawGUI()
    {
        GUI.DrawTexture(new Rect(PositionX, PositionY, Width, Height), Texture);
        GUI.Label(new Rect(PositionX, PositionY+Height, Width, 50.0f), name);
    }

    protected override Texture2D CreateTexture()
    {
        return Textures.Create2D(GetPixelData(), TextureSize, false, false);
    }

    private uint[] GetPixelData()
    {
        uint[] noise = new uint[TextureSize*TextureSize];
        for (int h=0; h<TextureSize; h++)
            for (int w=0; w<TextureSize; w++)
                noise[(h*TextureSize)+w] = GetPixel(w, h);
        return noise;
    }

    private uint GetPixel(int w, int h)
    {
        float u = (((float)w)+0.5f)/TextureSize;
        float v = (((float)h)+0.5f)/TextureSize;
        float n = GetNoiseSample(u*UVScale+UVShift, v*UVScale+UVShift)*NoiseScale+NoiseShift;
        return Colors.UInt32FromRGBA(n, n, n, 1.0f);
    }

    private float GetNoiseSample(float x, float y)
    {
        return PerlinDerivative.Noise2(x, y, Octaves, Lacunarity, Gain);
    }
}